package net.neptech.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.neptech.api.SystemApi;
import net.neptech.dto.workflow.PageDto;
import net.neptech.dto.sys.StaffDTO;
import net.neptech.dto.workflow.UserQueryDto;
import net.neptech.enums.workflow.InstanceConstant;
import net.neptech.enums.workflow.InstanceRecordStatusEnum;
import net.neptech.enums.workflow.NodeUserTypeEnum;
import net.neptech.model.dto.*;
import net.neptech.model.dto.node.Node;
import net.neptech.model.dto.node.parent.SuperUserRootNode;
import net.neptech.model.sys.Dept;
import net.neptech.model.vo.*;
import net.neptech.model.workflow.*;
import net.neptech.service.*;
import net.neptech.util.DateUtil;
import net.neptech.util.JsonUtil;
import net.neptech.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Saya
 * @Date 2025/8/24 14:19
 * @Description TODO
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class CombinationGroupServiceImpl implements CombinationGroupService {

    private final SystemApi systemApi;
    private final GroupService processGroupService;
    private final FlowableService flowableService;


//    private IUserService userService;


//    private IDeptUserService deptUserService;

    private final WorkflowMainService workflowMainService;


    private final WorkflowService workflowService;


    private final StarterService starterService;


    private final RemoteService remoteService;


    private final InstanceRecordService instanceRecordService;


    private final NodeDataService nodeDataService;

    private final InstanceCopyService instanceCopyService;

    /**
     * 根据部门id集合和角色id集合 获取用户列表
     */
    @Override
    public List<String> queryUserListByDeptIdListAndRoleIdList(List<String> deptIdList, List<String> roleIdList) {
        UserQueryDto userQueryDto = new UserQueryDto();
        userQueryDto.setDeptIdList(deptIdList.stream().map(Long::parseLong).collect(Collectors.toList()));
        userQueryDto.setRoleIdList(roleIdList.stream().map(Long::parseLong).collect(Collectors.toList()));
        List<String> userIds = systemApi.getUserIdsByDto(userQueryDto).getData();
        return userIds.stream().map(String::valueOf).collect(Collectors.toList());
    }

    /**
     * 查询表单组包含流程
     */
    @Override
    public List<FormGroupVo> listGroupWithProcess(Boolean hidden) {
        List<FormGroupVo> formGroupVos = new LinkedList<>();
        List<WorkflowGroup> groupList = processGroupService.lambdaQuery().orderByDesc(WorkflowGroup::getSort).list();
        groupList.forEach(group -> {
            FormGroupVo formGroupVo = FormGroupVo.builder().id((group.getId())).name(group.getGroupName()).items(new LinkedList<>()).build();
            formGroupVos.add(formGroupVo);
            List<Workflow> processList = workflowService.lambdaQuery().eq(Workflow::getGroupId, group.getId()).eq(hidden != null, Workflow::getHidden, hidden).eq(Workflow::getStop, false).orderByAsc(Workflow::getSort).orderByDesc(Workflow::getCreateTime).list();
            processList.forEach(workflow -> {
                formGroupVo.getItems().add(FormGroupVo.FlowVo.builder().flowId(workflow.getFlowId()).rangeShow(workflow.getRangeShow()).name(workflow.getFlowName()).logo(workflow.getIcon()).remark(workflow.getRemark()).stop(workflow.getStop()).uniqueId(workflow.getUniqueId()).updated(workflow.getUpdateTime()).build());
            });
        });
        return formGroupVos;
    }

    /**
     * 查询流程组和主流程
     */
    @Override
    public List<FormGroupVo> listGroupWithProcessMain() {
        List<FormGroupVo> formGroupVos = new LinkedList<>();
        List<WorkflowGroup> groupList = processGroupService.lambdaQuery().orderByDesc(WorkflowGroup::getSort).list();

        groupList.forEach(group -> {
            FormGroupVo formGroupVo = FormGroupVo.builder().id((group.getId())).name(group.getGroupName()).items(new LinkedList<>()).build();
            formGroupVos.add(formGroupVo);

            List<WorkflowMain> processMainList = workflowMainService.lambdaQuery().eq(WorkflowMain::getGroupId, group.getId()).orderByAsc(WorkflowMain::getSort).orderByDesc(WorkflowMain::getCreateTime).list();
            processMainList.forEach(processMain -> {
                List<Workflow> processList = workflowService.lambdaQuery().eq(Workflow::getUniqueId, processMain.getUniqueId()).eq(Workflow::getHidden, false).orderByDesc(Workflow::getUpdateTime).list();
                Workflow workflow = null;
                {
                    workflow = processList.stream().filter(w -> !w.getStop()).findAny().orElse(null);
                    if (workflow == null) {
                        workflow = processList.get(0);
                    }
                }
                Boolean reportEnable = false;
                formGroupVo.getItems().add(FormGroupVo.FlowVo.builder().flowId(workflow.getFlowId()).uniqueId(workflow.getUniqueId()).rangeShow(processMain.getRangeShow()).name(processMain.getName()).remark(workflow.getRemark()).logo(processMain.getLogo()).reportEnable(reportEnable).stop(workflow.getStop()).uniqueId(processMain.getUniqueId()).updated(processMain.getUpdateTime()).build());
            });
        });
        return formGroupVos;
    }

    /**
     * 搜索流程
     */
    @Override
    public List<FormGroupVo.FlowVo> searchFlowList(String word) {

        List<WorkflowMain> processMainList = workflowMainService.lambdaQuery().like(WorkflowMain::getName, word).orderByAsc(WorkflowMain::getSort).orderByDesc(WorkflowMain::getCreateTime).list();

        List<FormGroupVo.FlowVo> flowVoList = new ArrayList<>();


        for (WorkflowMain processMain : processMainList) {

            List<Workflow> processList = workflowService.lambdaQuery()

                    .eq(Workflow::getUniqueId, processMain.getUniqueId()).eq(Workflow::getHidden, false).orderByDesc(Workflow::getUpdateTime).list();

            Workflow workflow = null;
            {
                workflow = processList.stream().filter(w -> !w.getStop()).findAny().orElse(null);
                if (workflow == null) {
                    workflow = processList.get(0);
                }
            }
            FormGroupVo.FlowVo flowVo = FormGroupVo.FlowVo.builder().flowId(workflow.getFlowId()).uniqueId(workflow.getUniqueId()).rangeShow(processMain.getRangeShow()).name(processMain.getName()).remark(workflow.getRemark()).logo(processMain.getLogo()).reportEnable(false).stop(workflow.getStop()).uniqueId(processMain.getUniqueId()).updated(processMain.getUpdateTime()).build();

            flowVoList.add(flowVo);
        }

        return flowVoList;
    }

    /**
     * 查询所有我可以发起的表单组
     */
    @Override
    public List<FormGroupVo> listCurrentUserStartGroup() {

        String userId = SecurityUtils.getUserId().toString();
        log.info("当前登录用户：{}", userId);
        StaffDTO user = systemApi.getStaffByUserId(userId).getData();
        List<FormGroupVo> formGroupVos = new LinkedList<>();
        List<WorkflowGroup> groupList = processGroupService.lambdaQuery().orderByDesc(WorkflowGroup::getSort).list();
        groupList.forEach(group -> {
            FormGroupVo formGroupVo = FormGroupVo.builder().id((group.getId())).name(group.getGroupName()).items(new LinkedList<>()).build();
            formGroupVos.add(formGroupVo);

            List<Workflow> processList = workflowService.lambdaQuery().eq(Workflow::getGroupId, group.getId()).eq(Workflow::getHidden, false).eq(Workflow::getStop, false).orderByAsc(Workflow::getSort).list();

            Map<String, Boolean> existMap = new HashMap<>();

            if (!processList.isEmpty()) {
                List<Long> idList = processList.stream().map(Workflow::getFlowId).map(Long::parseLong).collect(Collectors.toList());
                //查询发起人集合
                List<WorkflowStarter> processStarterList = starterService.lambdaQuery().in(WorkflowStarter::getProcessId, idList).list();
                Map<String, List<WorkflowStarter>> groupmap = processStarterList.stream().collect(Collectors.groupingBy(WorkflowStarter::getProcessId));

                for (Workflow workflow : processList) {
                    List<WorkflowStarter> processStarters = groupmap.get(workflow.getFlowId());
                    if (processStarters == null) {
                        existMap.put(workflow.getFlowId(), true);
                        continue;
                    }
                    boolean match = processStarters.stream().anyMatch(w -> w.getStarterId().equals(userId) && w.getType().equals(NodeUserTypeEnum.USER.getKey()));
                    if (match) {
                        existMap.put(workflow.getFlowId(), true);
                        continue;
                    }
                    Set<String> deptIdSet = new HashSet<>();

                    //需要查询包含子级的部门id
                    List<String> queryChildrenDeptIdList = new ArrayList<>();
                    for (WorkflowStarter processStarter : processStarters) {
                        if (processStarter.getType().equals(NodeUserTypeEnum.DEPT.getKey())) {
                            deptIdSet.add(processStarter.getStarterId().toString());
                            //包含下级
                            if (processStarter.getContainChildrenDept()) {
                                queryChildrenDeptIdList.add(processStarter.getStarterId().toString());

                            }
                        }
                    }
                    Map<String, List<Dept>> childrenDeptMap = remoteService.batchQueryChildDeptList(queryChildrenDeptIdList.stream().map(Long::parseLong).toList());
                    for (Map.Entry<String, List<Dept>> entry : childrenDeptMap.entrySet()) {
                        Set<String> collect = entry.getValue().stream().map(Dept::getDeptId).map(String::valueOf).collect(Collectors.toSet());
                        deptIdSet.addAll(collect);
                    }
                    //判断部门交集
                    String userDeptIdList = user.getDeptId().toString();
                    if (deptIdSet.contains(userDeptIdList)) {
                        existMap.put(workflow.getFlowId(), true);
                    }
                }

            }
            processList.forEach(workflow -> {

                if (!existMap.get(workflow.getFlowId())) {
                    return;
                }
                formGroupVo.getItems().add(FormGroupVo.FlowVo.builder().flowId(workflow.getFlowId()).uniqueId(workflow.getUniqueId()).name(workflow.getFlowName()).logo(workflow.getIcon()).remark(workflow.getRemark()).stop(workflow.getStop()).updated(workflow.getUpdateTime()).build());
            });
        });
        return formGroupVos;
    }

    /**
     * 删除主流程
     */
    @Transactional
    @Override
    public void deleteProcessMain(String uniqueId) {
        workflowMainService.lambdaUpdate().eq(WorkflowMain::getUniqueId, uniqueId).remove();
        workflowService.lambdaUpdate().set(Workflow::getHidden, true).eq(Workflow::getHidden, false).eq(Workflow::getUniqueId, uniqueId).update(new Workflow());
    }

    /**
     * 清理所有流程
     */
    @Transactional
    @Override
    public void clear(String uniqueId) {
        return;
    }

    /**
     * 查询当前登录用户的待办任务
     */
    @Override
    public PageResultDto<TaskDto> queryTodoTaskList(PageDto pageVO) {

        TaskQueryParamDto taskQueryParamDto = BeanUtil.copyProperties(pageVO, TaskQueryParamDto.class);
        taskQueryParamDto.setAssign(SecurityUtils.getUserId().toString());

        PageResultDto<TaskDto> pageResultDto = flowableService.queryTodoTask(taskQueryParamDto);
        List<TaskDto> records = pageResultDto.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResultDto;
        }
        Set<String> processInstanceIdSet = records.stream().map(TaskDto::getProcessInstanceId).collect(Collectors.toSet());
        //流程实例记录
        List<InstanceRecord> processInstanceRecordList = instanceRecordService.lambdaQuery().in(InstanceRecord::getProcessInstanceId, processInstanceIdSet).list();
        //发起人
        Set<String> startUserIdSet = processInstanceRecordList.stream().map(InstanceRecord::getUserId).collect(Collectors.toSet());
        List<StaffDTO> startUserList = new ArrayList<>();
        {
            for (String userIds : startUserIdSet) {
                StaffDTO user = systemApi.getStaffByUserId(userIds).getData();
                startUserList.add(user);
            }
        }
        //流程配置
        Set<String> flowIdSet = processInstanceRecordList.stream().map(InstanceRecord::getFlowId).collect(Collectors.toSet());
        List<Workflow> processList = workflowService.lambdaQuery().in(Workflow::getFlowId, flowIdSet).list();
        for (TaskDto record : records) {
            InstanceRecord instanceRecord = processInstanceRecordList.stream().filter(w -> StrUtil.equals(w.getProcessInstanceId(), record.getProcessInstanceId())).findAny().orElse(null);
            if (instanceRecord != null) {

                record.setProcessName(instanceRecord.getName());

                StaffDTO startUser = startUserList.stream().filter(w -> w.getUserId().equals(instanceRecord.getUserId())).findAny().orElse(null);

                record.setRootUserId(instanceRecord.getUserId().toString());
                record.setGroupName(instanceRecord.getGroupName());
                if (startUser != null) {
                    record.setRootUserName(startUser.getStaffName());
                }
                if (startUser != null) {
                    record.setRootUserAvatarUrl(startUser.getAvatar());
                }
                record.setStartTime(instanceRecord.getCreateTime());
                record.setStartTimeShow(DateUtil.dateShow(instanceRecord.getCreateTime()));
                record.setProcessInstanceBizCode(instanceRecord.getProcessInstanceBizCode());
            }
            //进行中  查询谁在处理
            TaskParamDto variableQueryParamDto = new TaskParamDto();
            variableQueryParamDto.setNodeId(null);
            variableQueryParamDto.setProcessInstanceId(record.getProcessInstanceId());
            List<TaskDto> taskDtoList = flowableService.queryTaskAssignee(variableQueryParamDto);
            if (!taskDtoList.isEmpty()) {
                //正则处理人
                Set<String> taskAssign = taskDtoList.stream().map(TaskDto::getAssign).collect(Collectors.toSet());
                String taskAssignId = CollUtil.newArrayList(taskAssign).get(0);
                StaffDTO userDto1 = systemApi.getStaffByUserId(taskAssignId).getData();
                if (taskAssign.size() == 1) {
                    record.setTaskAssignShow(userDto1.getStaffName());
                } else {
                    String format = StrUtil.format("{}等{}人", userDto1.getStaffName(), taskAssign.size());
                    record.setTaskAssignShow(format);
                }
            }
            //是否是子流程发起任务
            Map<String, Object> paramMap = record.getParamMap();
            //处理表单数据
            Workflow workflow = processList.stream().filter(w -> StrUtil.equals(w.getFlowId(), record.getFlowId())).findAny().orElse(null);
            if (workflow != null) {
                List<Dict> formValueShowList = getFormValueShowList(workflow, record.getFlowId(), record.getNodeId(), paramMap);
                record.setFormValueShowList(formValueShowList);
            }
        }
        return pageResultDto;
    }

    /**
     * 查询已办任务
     */
    @Override
    public PageResultDto<TaskDto> queryFinishedTaskList(DataQueryVO pageVO) {
        TaskQueryParamDto taskQueryParamDto = BeanUtil.copyProperties(pageVO, TaskQueryParamDto.class);
        taskQueryParamDto.setAssign(SecurityUtils.getUserId().toString());
        PageResultDto<TaskDto> pageResultDto = flowableService.queryCompletedTask(taskQueryParamDto);
        List<TaskDto> records = pageResultDto.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResultDto;
        }
        Set<String> processInstanceIdSet = records.stream().map(TaskDto::getProcessInstanceId).collect(Collectors.toSet());

        //流程实例记录
        List<InstanceRecord> processInstanceRecordList = instanceRecordService.lambdaQuery().in(InstanceRecord::getProcessInstanceId, processInstanceIdSet).list();

        //发起人
        Set<String> startUserIdSet = processInstanceRecordList.stream().map(InstanceRecord::getUserId).map(String::valueOf).collect(Collectors.toSet());

        List<StaffDTO> startUserList = new ArrayList<>();
        {
            for (String userIds : startUserIdSet) {
                StaffDTO user = systemApi.getStaffByUserId(userIds).getData();
                startUserList.add(user);
            }
        }
        //流程配置
        Set<String> flowIdSet = processInstanceRecordList.stream().map(InstanceRecord::getFlowId).collect(Collectors.toSet());
        List<Workflow> processList = workflowService.lambdaQuery().in(Workflow::getFlowId, flowIdSet).list();

        for (TaskDto record : records) {

            InstanceRecord instanceRecord = processInstanceRecordList.stream().filter(w -> StrUtil.equals(w.getProcessInstanceId(), record.getProcessInstanceId())).findAny().orElse(null);

            if (instanceRecord != null) {

                record.setProcessName(instanceRecord.getName());
                StaffDTO startUser = startUserList.stream().filter(w -> w.getUserId().equals(instanceRecord.getUserId())).findAny().orElse(null);
                record.setRootUserId(instanceRecord.getUserId().toString());
                record.setGroupName(instanceRecord.getGroupName());
                if (startUser != null) {
                    record.setRootUserName(startUser.getStaffName());
                }
                if (startUser != null) {
                    record.setRootUserAvatarUrl(startUser.getAvatar());
                }
                record.setStartTime(instanceRecord.getCreateTime());
                record.setStartTimeShow(DateUtil.dateShow(instanceRecord.getCreateTime()));
                record.setProcessInstanceResult(instanceRecord.getResult());
                record.setProcessInstanceBizCode(instanceRecord.getProcessInstanceBizCode());


                if (instanceRecord.getStatus() == InstanceRecordStatusEnum.ON_GOING.getCode()) {

                    //进行中  查询谁在处理
                    TaskParamDto variableQueryParamDto = new TaskParamDto();
                    variableQueryParamDto.setNodeId(null);
                    variableQueryParamDto.setProcessInstanceId(record.getProcessInstanceId());
                    List<TaskDto> taskDtoList = flowableService.queryTaskAssignee(variableQueryParamDto);
                    if (!taskDtoList.isEmpty()) {
                        //正则处理人
                        Set<String> taskAssign = taskDtoList.stream().map(TaskDto::getAssign).collect(Collectors.toSet());
                        String taskAssignId = CollUtil.newArrayList(taskAssign).get(0);
                        StaffDTO userDto1 = systemApi.getStaffByUserId(taskAssignId).getData();
                        if (taskAssign.size() == 1) {
                            record.setTaskAssignShow(userDto1.getStaffName());
                        } else {
                            String format = StrUtil.format("{}等{}人", userDto1.getStaffName(), taskAssign.size());
                            record.setTaskAssignShow(format);
                        }
                    }
                }


                //查询流程实例变量
                VariableQueryParamDto v = new VariableQueryParamDto();
                v.setExecutionId(instanceRecord.getProcessInstanceId());
                Map<String, Object> paramMap = flowableService.queryVariables(v);

                //处理表单数据
                Workflow workflow = processList.stream().filter(w -> StrUtil.equals(w.getFlowId(), record.getFlowId())).findFirst().orElse(null);
                List<Dict> formValueShowList = null;
                if (workflow != null) {
                    formValueShowList = getFormValueShowList(workflow, record.getFlowId(), record.getNodeId(), paramMap);
                }
                record.setFormValueShowList(formValueShowList);
            }
        }
        return pageResultDto;
    }

    /**
     * 查询我发起的
     */
    @Override
    public Page queryInitiatedTaskList(DataQueryVO pageDto) {


        String userId = SecurityUtils.getUserId().toString();

        //查询所有的流程id
        List<String> allFlowIdList = new ArrayList<>();
        if (CollUtil.isNotEmpty(pageDto.getFlowIdList())) {
            List<String> data = workflowService.getAllRelatedFlowId(pageDto.getFlowIdList());
            allFlowIdList.addAll(data);
        }
        Page<InstanceRecord> instanceRecordPage = instanceRecordService.lambdaQuery().eq(InstanceRecord::getUserId, userId).in(CollUtil.isNotEmpty(allFlowIdList), InstanceRecord::getFlowId, allFlowIdList).orderByDesc(InstanceRecord::getCreateTime).page(new Page<>(pageDto.getPageNum(), pageDto.getPageSize()));

        List<InstanceRecord> records = instanceRecordPage.getRecords();
        if (CollUtil.isEmpty(records)) {
            return instanceRecordPage;
        }


        //流程配置
        Set<String> flowIdSet = records.stream().map(InstanceRecord::getFlowId).collect(Collectors.toSet());
        List<Workflow> processList = workflowService.lambdaQuery().in(Workflow::getFlowId, flowIdSet).list();

        List<InstanceRecordVO> processInstanceRecordVOList = BeanUtil.copyToList(records, InstanceRecordVO.class);

        StaffDTO userDto = systemApi.getStaffByUserId(userId).getData();

        for (InstanceRecordVO record : processInstanceRecordVOList) {

            //处理表单数据
            Workflow workflow = processList.stream().filter(w -> StrUtil.equals(w.getFlowId(), record.getFlowId())).findFirst().get();


            record.setFormData(null);
            record.setProcess(null);
            record.setStartTimeShow(DateUtil.dateShow(record.getCreateTime()));
            record.setRootUserAvatarUrl(userDto.getAvatar());
            record.setRootUserName(userDto.getStaffName());
            record.setCancelEnable(false);
            record.setFlowUniqueId(workflow.getUniqueId());

            //查询流程变量
            VariableQueryParamDto v = new VariableQueryParamDto();
            v.setExecutionId(record.getProcessInstanceId());
            Map<String, Object> paramMap = flowableService.queryVariables(v);
            List<Dict> formValueShowList = getFormValueShowList(workflow, record.getFlowId(), InstanceConstant.VariableKey.START_NODE, paramMap);
            record.setFormValueShowList(formValueShowList);

            if (record.getStatus() == InstanceRecordStatusEnum.ON_GOING.getCode()) {


                TaskParamDto variableQueryParamDto = new TaskParamDto();
                variableQueryParamDto.setNodeId(null);
                variableQueryParamDto.setProcessInstanceId(record.getProcessInstanceId());
                List<TaskDto> taskDtoList = flowableService.queryTaskAssignee(variableQueryParamDto);
                if (!taskDtoList.isEmpty()) {
                    //正则处理人
                    Set<String> taskAssign = taskDtoList.stream().map(TaskDto::getAssign).collect(Collectors.toSet());
                    String taskAssignId = CollUtil.newArrayList(taskAssign).get(0);
                    StaffDTO userDto1 = systemApi.getStaffByUserId(taskAssignId).getData();
                    if (taskAssign.size() == 1) {
                        record.setTaskAssignShow(userDto1.getStaffName());
                    } else {
                        String format = StrUtil.format("{}等{}人", userDto1.getStaffName(), taskAssign.size());
                        record.setTaskAssignShow(format);
                    }
                }
            }
        }
        Page<InstanceRecordVO> page = new Page<>();
        BeanUtil.copyProperties(instanceRecordPage, page);
        page.setRecords(processInstanceRecordVOList);
        return page;
    }

    /**
     * 查询抄送给我的
     */
    @Override
    public Page queryCopiedTaskList(DataQueryVO pageDto) {


        String userId = SecurityUtils.getUserId().toString();

        Page<InstanceCopy> page = instanceCopyService.lambdaQuery().eq(InstanceCopy::getUserId, userId).in(CollUtil.isNotEmpty(pageDto.getFlowIdList()), InstanceCopy::getFlowId, pageDto.getFlowIdList()).orderByDesc(InstanceCopy::getNodeTime).page(new Page<>(pageDto.getPageNum(), pageDto.getPageSize()));

        List<InstanceCopy> records = page.getRecords();

        List<InstanceCopyVo> processCopyVoList = BeanUtil.copyToList(records, InstanceCopyVo.class);

        if (CollUtil.isNotEmpty(records)) {

            //发起人
            Set<String> startUserIdSet = records.stream().map(InstanceCopy::getStartUserId).map(String::valueOf).collect(Collectors.toSet());

            List<StaffDTO> startUserList = new ArrayList<>();
            for (String s : startUserIdSet) {
                StaffDTO user = systemApi.getStaffByUserId(s).getData();
                startUserList.add(user);
            }
            Set<String> processInstanceIdSet = records.stream().map(InstanceCopy::getProcessInstanceId).collect(Collectors.toSet());

            //流程实例记录
            List<InstanceRecord> processInstanceRecordList = instanceRecordService.lambdaQuery().in(InstanceRecord::getProcessInstanceId, processInstanceIdSet).list();

            //流程配置
            Set<String> flowIdSet = processInstanceRecordList.stream().map(InstanceRecord::getFlowId).collect(Collectors.toSet());
            List<Workflow> processList = workflowService.lambdaQuery().in(Workflow::getFlowId, flowIdSet).list();


            for (InstanceCopyVo record : processCopyVoList) {

                InstanceRecord instanceRecord = processInstanceRecordList.stream().filter(w -> StrUtil.equals(w.getProcessInstanceId(), record.getProcessInstanceId())).findFirst().get();


                StaffDTO startUser = startUserList.stream().filter(w -> w.getUserId().equals(record.getStartUserId())).findAny().orElse(null);
                if (startUser != null) {
                    record.setStartUserName(startUser.getStaffName());
                }
                if (startUser != null) {
                    record.setStartUserAvatarUrl(startUser.getAvatar());
                }


                Workflow workflow = processList.stream().filter(w -> StrUtil.equals(w.getFlowId(), record.getFlowId())).findFirst().orElse(null);

                List<Dict> formValueShowList = getFormValueShowList(workflow, record.getFlowId(), InstanceConstant.VariableKey.START_NODE, JsonUtil.parseObject(record.getFormData(), new JsonUtil.TypeReference<Map<String, Object>>() {
                }));

                record.setFormValueShowList(formValueShowList);
                record.setFormData(null);
                record.setStartTimeShow(DateUtil.dateShow(instanceRecord.getCreateTime()));
                record.setProcessInstanceResult(instanceRecord.getResult());
                record.setProcessInstanceBizCode(instanceRecord.getProcessInstanceBizCode());

                if (instanceRecord.getStatus() == InstanceRecordStatusEnum.ON_GOING.getCode()) {


                    //进行中  查询谁在处理
                    TaskParamDto variableQueryParamDto = new TaskParamDto();
                    variableQueryParamDto.setNodeId(null);
                    variableQueryParamDto.setProcessInstanceId(record.getProcessInstanceId());
                    List<TaskDto> taskDtoList = flowableService.queryTaskAssignee(variableQueryParamDto);
                    if (!taskDtoList.isEmpty()) {
                        //正则处理人
                        Set<String> taskAssign = taskDtoList.stream().map(TaskDto::getAssign).collect(Collectors.toSet());
                        String taskAssignId = CollUtil.newArrayList(taskAssign).get(0);
                        StaffDTO userDto1 = systemApi.getStaffByUserId(taskAssignId).getData();
                        if (taskAssign.size() == 1) {
                            record.setTaskAssignShow(userDto1.getStaffName());
                        } else {
                            String format = StrUtil.format("{}等{}人", userDto1.getStaffName(), taskAssign.size());
                            record.setTaskAssignShow(format);
                        }
                    }
                }
            }
        }
        Page p = BeanUtil.copyProperties(page, Page.class);
        p.setRecords(processCopyVoList);
        return p;
    }

    /**
     * 获取列表 显示的表单数据 姓名：张三 格式
     */
    private List<Dict> getFormValueShowList(Workflow workflow, String flowId, String nodeId, Map<String, Object> paramMap) {
        String formItems = workflow.getFormConfig();
        List<FormVO> formItemVOList = JsonUtil.parseArray(formItems, FormVO.class);

        Map<String, String> formPermMap = new HashMap<>();

        if (StrUtil.isNotBlank(nodeId)) {
            Node node = nodeDataService.getNode(flowId, nodeId);
            SuperUserRootNode superUserRootNode = (SuperUserRootNode) node;
            Map<String, String> map = superUserRootNode.getFormPerms();
        } else {
            for (FormVO formItemVO : formItemVOList) {
                formPermMap.put(formItemVO.getFormId(), InstanceConstant.FormPermClass.READ);
            }
        }
        List<Dict> formValueShowList = new ArrayList<>();
        buildFormValueShow(paramMap, formItemVOList, formPermMap, formValueShowList);
        return formValueShowList.size() > 3 ? (formValueShowList.subList(0, 3)) : formValueShowList;
    }

    private static void buildFormValueShow(Map<String, Object> paramMap, List<FormVO> formItemVOList, Map<String, String> formPermMap, List<Dict> formValueShowList) {
        for (FormVO formItemVO : formItemVOList) {

            String id = formItemVO.getFormId();
            String formItemVOName = formItemVO.getFormName();

            String perm = formPermMap.get(id);
            if (StrUtil.isBlank(perm) || InstanceConstant.FormPermClass.HIDE.equals(perm)) {
                continue;
            }
            Object o = paramMap.get(id);
            if (o == null || StrUtil.isBlankIfStr(o)) {
                formValueShowList.add(Dict.create().set("key", formItemVOName).set("label", ""));
                continue;
            }
            //表单类型
            String type = formItemVO.getFormType();
            {
                if (StrUtil.isBlankIfStr(o)) {
                    formValueShowList.add(Dict.create().set("key", formItemVOName).set("label", ""));
                    return;
                }
            }
        }
    }
}
